package com.my.lucky.repository;

import com.my.lucky.model.Gainian60Boll;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Repository
public interface Gainian60BollRepository extends JpaRepository<Gainian60Boll, Long> {

    /**
     * 查询指定股票最近N天的数据
     */
    @Query("SELECT s FROM Gainian60Boll s WHERE s.code = :code " +
            "AND s.tradeDate >= :tradeDate ORDER BY s.tradeDate DESC")
    List<Gainian60Boll> findRecentDataByCode(
            @Param("code") String code,
            @Param("tradeDate") LocalDate startDate);

    /**
     * 根据code和tradeDate查询记录
     */
    Optional<Gainian60Boll> findByCodeAndTradeDate(String code, LocalDate tradeDate);

    /**
     * 批量保存或更新
     * 当记录存在时，只更新非null的字段
     */
    @Transactional
    default <S extends Gainian60Boll> Iterable<S> saveOrUpdateAll(Iterable<S> entities) {
        if (entities == null) {
            return Collections.emptyList();
        }

        List<S> resultList = new ArrayList<>();
        for (S entity : entities) {
            resultList.add(saveOrUpdate(entity));
        }
        return resultList;
    }

    /**
     * 保存或更新单个实体
     * 当记录存在时，只更新非null的字段
     */
    @Transactional
    default <S extends Gainian60Boll> S saveOrUpdate(S entity) {
        if (entity == null || entity.getCode() == null || entity.getTradeDate() == null) {
            throw new IllegalArgumentException("Code and tradeDate cannot be null");
        }

        Optional<Gainian60Boll> existingOptional = findByCodeAndTradeDate(
                entity.getCode(), entity.getTradeDate());

        if (existingOptional.isPresent()) {
            // 记录存在，只更新非null字段
            Gainian60Boll existing = existingOptional.get();

            // 更新基本信息（如果不为null）
            if (entity.getName() != null) {
                existing.setName(entity.getName());
            }

            // 更新Bollinger Bands值（如果不为null）
            if (entity.getBollMid() != 0) {
                existing.setBollMid(entity.getBollMid());
            }
            if (entity.getBollLower() != 0) {
                existing.setBollLower(entity.getBollLower());
            }
            if (entity.getBollUpper() != 0) {
                existing.setBollUpper(entity.getBollUpper());
            }

            // 更新时间点数据（如果不为null）
            if (entity.getBoll9() != null && !entity.getBoll9().trim().isEmpty()) {
                existing.setBoll9(entity.getBoll9());
            }
            if (entity.getBoll10() != null  && !entity.getBoll10().trim().isEmpty()) {
                existing.setBoll10(entity.getBoll10());
            }
            if (entity.getBoll11() != null  && !entity.getBoll11().trim().isEmpty()) {
                existing.setBoll11(entity.getBoll11());
            }
            if (entity.getBoll13() != null  && !entity.getBoll13().trim().isEmpty()) {
                existing.setBoll13(entity.getBoll13());
            }
            if (entity.getBoll14() != null  && !entity.getBoll14().trim().isEmpty()) {
                existing.setBoll14(entity.getBoll14());
            }
            if (entity.getBoll15() != null  && !entity.getBoll15().trim().isEmpty()) {
                existing.setBoll15(entity.getBoll15());
            }

            return (S) save(existing);
        } else {
            // 记录不存在，直接保存
            return save(entity);
        }
    }
    
}